<?php

/*
 * 消息推送类
 */
class pushModel 
{
    public function __construct(& $base)
    {
        $this->base = $base;
        $this->db = & $this->base->db;
        $this->redis = & $this->base->redis;
        $this->apnsArr = $this->base->config['App_PUSH_INFO'];//推送相关配置
        
    }
    /**
     * 执行推送任务
     * @param $data  array 推送任务信息
     * @param $p  int 分批执行推送任务的批次
     * @return 
     */
    public function goPushMessage($data)
    {
        if(!isset($data['msg_id'])) return false;

        $msg_id = $data['msg_id'];
        $pushStatus = $this->redis->hgetall(REDIS_PREFIX.'PushStatus_'.$msg_id);

        if(empty($pushStatus) || $data['status'] == '0')
        {
            $pushStatus = array('batch' => 1, 'android' => 0, 'ios' => 0, 'android_mi' => 0, 'ios_mi' => 0);
            $this->redis->hmset(REDIS_PREFIX .'PushStatus_'.$msg_id, $pushStatus);
            $this->db->updateRowTable('r_msg_push', array('msg_id'=>$msg_id,'status'=>1));
            $batch = 1;
        }
        elseif($data['status'] == '1')
        {
            if(empty($pushStatus))
            {
                $pushStatus = array('batch' => 1, 'android' => 0, 'ios' => 0, 'android_mi' => 0, 'ios_mi' => 0);
                $this->redis->hmset(REDIS_PREFIX .'PushStatus_'.$msg_id, $pushStatus);
            }
            $batch = $pushStatus['batch'];
        }
        else
        {
            $this->db->updateRowTable('r_msg_push', array('msg_id'=>$msg_id,'status'=>2));
            return false;
        }

        //获取要推送的设备
        echo $msg_id.'-'.$batch."\n";
        $clients = $this->getClients($data, $msg_id, $batch);
        $this->redis->hincrby(REDIS_PREFIX.'PushStatus_'.$msg_id, 'batch', 1);
        $culr = $this->apnsArr['host'].':'.$this->apnsArr['port'];

        // 发送Android通知
        $androidData = array(
            'clients' => array(),
            'expiry' => time() + 3600,
            'payload' => array(
                'aps' => array(
                    'alert' => array(
                        'body' => $data['android_message'],
                        'title' => $data['title'],
                        'action-loc-key' => '',
                        'loc-key' => '',
                        'loc-args' => '',
                        'launch-image' => '',
                        ),
                    // 'badge' => 3,
                    'sound' => $data['is_sound'],
                    ),
                'url' => $data['url'],//推送的地址
                'args' => "",
            ),
        );

        //ios消息推送
        $iosData = array(
            'tokens' => array(),
            'expiry' => time() + 1800,
            'payload' => array(
                'aps' => array(
                    'alert' => array(
                        'body' => $data['ios_message'],
                        'action-loc-key' => '',
                        'loc-key' => '',
                        'loc-args' => '',
                        'launch-image' => 'LaunchImage',
                        ),
                    // 'badge' => 1,
                    'sound' => $data['is_sound'],
                ),
                'url' => $data['url'],
            ),
        );

        $android_post_curl = "http://".$culr.'/droid/notific/'.$this->apnsArr['appIdentifier'];
        $ios_post_curl = "http://".$culr.'/ios/notific/'.$this->apnsArr['appIdentifier'];

        $status = 1;//推送的状态
        $is_success = 1;
        $token = array();

        $mipush = $this->base->loadLib('mipush');

        echo 'begin send,',date('Y-m-d H:i:s'),"\n";
        switch ($data['device_type'])
        {
            case 1:
                if(empty($clients) || (empty($client['android']) && empty($client['android_mi'])))
                {
                    $status = 2;
                    break;
                }

                echo "only android begin, status:{$status},",time(),"\n";
                if(!empty($clients['android']))
                {
                    foreach ($clients['android'] as $key => $v)
                    {
                        $androidData['clients'] = $v;
                        $postResult = $this->post($android_post_curl, json_encode($androidData)) == '"+OK"' ? 1 : 0;
                        $is_success *=  $postResult;
                    }
                    $status = $is_success == 1 ? 2 : 1;
                }

                if(!empty($clients['android_mi']))
                {
                    foreach ($clients['android_mi'] as $key => $v)
                    {
                        $mi_clients = $v;
                        $postResult = $mipush->send($mi_clients, $androidData['payload']);
                        $is_success = $postResult['result'] == 'ok';
                    }
                    $status = $is_success ? 2 : 1;
                }

                break;

            case 2:
                if(empty($clients) || (empty($client['ios']) && empty($client['ios_mi'])) )
                {
                    $status = 2;
                    break;
                }

                echo "only ios begin, status:{$status},",time(),"\n";
                if(!empty($clients['ios']))
                {
                    foreach ($clients['ios'] as $key => $v)
                    {
                        $iosData['tokens'] = $v;
                        $postResult = $this->post($ios_post_curl, json_encode($iosData)) == '"+OK"' ? 1 : 0;
                        $is_success *=  $postResult;
                    }
                    $status = $is_success == 1 ? 2 : 1;
                }

                if(!empty($clients['ios_mi']))
                {
                    foreach ($clients['ios_mi'] as $key => $v)
                    {
                        $mi_clients = $v;
                        $postResult = $mipush->send($mi_clients, $iosData['payload'], 1);
                        $is_success = $postResult['result'] == 'ok';
                    }
                    $status = $is_success ? 2 : 1;
                }

                break;

            case 0:
                $status = 0;

                echo "android in both begin, status:{$status},",time(),"\n";
                if(!empty($clients['android']))
                {
                    if(!empty($clients['android']['android']))
                    {
                        echo "\nmemory:",memory_get_usage(),',android:';
                        foreach ($clients['android']['android'] as $k=>$v)
                        {
                            echo $k,',',$v[0],',';
                            $androidData['clients'] = $v;
                            $postResult = $this->post($android_post_curl, json_encode($androidData)) == '"+OK"' ? 1 : 0;
                            $is_success *=  $postResult;
                        }
                    }

                    if(!empty($clients['android']['android_mi']))
                    {
                        echo "\nmemory:",memory_get_usage(),'android_mi:';
                        foreach ($clients['android']['android_mi'] as $k=>$v)
                        {
                            echo $k,',',$v[0],',';
                            $mi_clients = $v;
                            $postResult = $mipush->send($mi_clients, $androidData['payload']);
                            $is_success = $postResult['result'] == 'ok';
                        }
                    }
                }
                $status += 1;

                echo "\nios in both begin, status:{$status},",time(),"\n";
                if(!empty($clients['ios']))
                {
                    if(!empty($clients['ios']['ios']))
                    {
                        echo "\nmemory:",memory_get_usage(),'ios:';
                        foreach ($clients['ios'] as $k=>$v)
                        {
                            echo $k,',',$v[0],',';
                            $iosData['tokens'] = $v;
                            $postResult = $this->post($ios_post_curl, json_encode($iosData)) == '"+OK"' ? 1 : 0;
                            $is_success *=  $postResult;
                        }
                    }

                    if(!empty($clients['ios']['ios_mi']))
                    {
                        echo "\nmemory:",memory_get_usage(),'ios_mi:';
                        foreach ($clients['ios']['ios_mi'] as $k=>$v)
                        {
                            echo $k,',',$v[0],',';
                            $mi_clients = $v;
                            $postResult = $mipush->send($mi_clients, $iosData['payload'], 1);
                            $is_success = $postResult['result'] == 'ok';
                        }
                    }
                }
                
                $status += 1;
                break;

            default:
                echo '参数不合法';
                exit;
                break;
        }
        echo "send end, status:{$status},",time(),',memory:',memory_get_usage(),"\n";

        if($status == 2)
        {
            //修改任务状态
            $updateData = array(
                'msg_id' => $msg_id,
                'status' => 2,
                'finish_time' => time(),
                'android_total' => $this->redis->hget(REDIS_PREFIX.'PushStatus_'.$msg_id, 'android'),
                'android_mi_total' => $this->redis->hget(REDIS_PREFIX.'PushStatus_'.$msg_id, 'android_mi'),
                'ios_total' => $this->redis->hget(REDIS_PREFIX.'PushStatus_'.$msg_id, 'ios'),
                'ios_mi_total' => $this->redis->hget(REDIS_PREFIX.'PushStatus_'.$msg_id, 'ios_mi'),
            );

            $this->db->updateRowTable('r_msg_push', $updateData);
            $this->redis->del(REDIS_PREFIX.'PushStatus_'.$data['msg_id']);
        }

        return $status;
    }

    //发送请求或获取信息
    public function post($url, $param = '', $method = 'POST')
    {
        if ($method == "GET") {
            $post_body = http_build_query($param);
            $url = $url . '?' . $post_body;
        } else {
            $post_body = is_array($param)?http_build_query($param):($param);
        }

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        if ($method == "POST") {
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $post_body);
        }
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($post_body))
        );
        curl_setopt($curl, CURLOPT_VERBOSE, true);

        $result = curl_exec($curl);
        curl_close($curl);
        /* 记录日志*/
        if(!is_array($param))
        {
            $data = @json_decode($param, true);

            $logInfo = '['.date('Y-m-d H:i:s')."]\tRESULT:".$result."\t";

            //!empty($data['clients']) && $logInfo .= 'clients:['.implode(',', $data['clients'])."]\t";
            //!empty($data['tokens']) && $logInfo .= 'tokens:['.implode(',', $data['tokens'])."]\t";

            $logInfo .= "\n";

            $this->base->load('log')->writeLog('pushlog', $logInfo,'push.txt');
        }
        // end
        return $result;
    }
    
   
    //获取要发送的设备
    private function getClients($data,$msg_id = 0, $batch=1, $listNum = 100000, $inPushList=[])
    {
        $type = $data['device_type'];
		set_time_limit(0);
        $result = array();

        if(empty($batch) || empty($msg_id))
        {
            return $result;
        }

        $notPushList = $this->redis->smembers(REDIS_PREFIX . 'clientNotReceivePush');

        $extra_sql = '';
        if($notPushList)
        {
            $extra_sql = ' and cid not'. $this->db_create_in($notPushList);
        }
        
        if(empty($inPushList)){
            $where = '';
            if($data['uids']){
                $where .= " and uid IN ('".str_replace('|',"','",$data['uids'])."')";
            }else{
                if($data['city']){
                    $where .= " and city='{$data['city']}'";
                }
                if($data['gender']){
                    $where .= " and gender='{$data['gender']}'";
                }
            }
            $rows = $this->db->getAll("select cid,lastcid from r_user where 1 $where");
            foreach($rows as $row){
                if($row['cid']){
                    $inPushList[] = $row['cid'];
                }elseif($row['lastcid']){
                    $inPushList[] = $row['lastcid'];
                }
            }
        }
        
        if($inPushList){
            $extra_sql = ' and cid'. $this->db_create_in($inPushList);
        }

        if($type == 0)
        {
            $data['device_type'] = 1;
            $result['android'] = $this->getClients($data, $msg_id, $batch, $listNum, $inPushList);
            $data['device_type'] = 2;
            $result['ios'] = $this->getClients($data, $msg_id, $batch, $listNum, $inPushList);
        }
        else if($type == 1)
        {
            $andTestClient = $this->redis->hget(REDIS_PREFIX . 'PushTest', $msg_id.'_and');
            if(!empty($andTestClient))
            {
                $andTestClient = explode('|', $andTestClient);
                $adsql = "select distinct(client) from r_client where client ".$this->db_create_in($andTestClient).' and client_type=1 and isPushVaild=1 and isAcceptPush=1 and version<2610';
                $misql = "select distinct(client) from r_client where client ".$this->db_create_in($andTestClient).' and client_type=1 and isPushVaild=1 and isAcceptPush=1 and version>=2610';
            }
            else{
                $adsql = 'select distinct(client) from r_client where client_type=1 and isPushVaild=1 and isAcceptPush=1 and version<2610';
                $misql = 'select distinct(client) from r_client where client_type=1 and isPushVaild=1 and isAcceptPush=1 and version>=2610';
            }
            if(isset($extra_sql)){
                $adsql .= $extra_sql;
                $misql .= $extra_sql;
            }
            //$droid_clients = $this->db->getCol($adsql);
            $droid_clients = [];
            $mi_clients = $this->db->getCol($misql);
            $this->redis->hincrby(REDIS_PREFIX.'PushStatus_'.$msg_id, 'android', count($droid_clients));
            $this->redis->hincrby(REDIS_PREFIX.'PushStatus_'.$msg_id, 'android_mi', count($mi_clients));
            //$result['android'] = array_chunk($droid_clients, 2000);
            $result['android'] = [];
            $result['android_mi'] = array_chunk($mi_clients, 1000);
            unset($droid_clients, $mi_clients);
        }
        else if($type == 2)
        {
            $iosTestClient = $this->redis->hget(REDIS_PREFIX . 'PushTest', $msg_id.'_ios');
            if(!empty($iosTestClient))
            {
                $iosTestClient = explode('|', $iosTestClient);
                $iosql = "select distinct(push_token) from r_client where client_type=2 and isPushVaild=1 and push_token!='' and version<2600 and client ".$this->db_create_in($iosTestClient) . $extra_sql;
                $misql = "select distinct(client) from r_client where client_type=2 and isPushVaild=1 and push_token!='' and version>=2600 and client ".$this->db_create_in($iosTestClient) . " $extra_sql group by push_token order by cid desc" ;
            }
            else{
                $iosql = "select distinct(push_token) from r_client where client_type=2 and isPushVaild=1 and isAcceptPush=1 and push_token != '' and version<2600".$extra_sql;
                $misql = "select distinct(client) from r_client where client_type=2 and isPushVaild=1 and isAcceptPush=1 and push_token != '' and version>=2600 $extra_sql group by push_token order by cid desc";
            }
            //$ios_token = $this->db->getCol($iosql);
            $ios_token = [];
            $mi_clients = $this->db->getCol($misql);
            $this->redis->hincrby(REDIS_PREFIX.'PushStatus_'.$msg_id, 'ios', count($ios_token));
            $this->redis->hincrby(REDIS_PREFIX.'PushStatus_'.$msg_id, 'ios_mi', count($mi_clients));
            //$result['ios'] = array_chunk($ios_token, 2000);
            $result['ios'] = [];
            $result['ios_mi'] = array_chunk($mi_clients, 1000);
            unset($ios_token, $mi_clients);
        }

        return $result;
    }

    // 通知消息未送达 的全部 client/token
    public function getFailedClient()
    {
        set_time_limit(0);
        $culr = $this->apnsArr['host'].':'.$this->apnsArr['port'];
        $androidFailedCurl = "http://".$culr.'/droid/feedback/'.$this->apnsArr['appIdentifier'];
        $iosFailedCurl = "http://".$culr.'/ios/feedback/'.$this->apnsArr['appIdentifier'];
        $iosInvalidCurl = "http://".$culr.'/ios/invtoken/'.$this->apnsArr['appIdentifier'];
        $clients = $this->post($androidFailedCurl,array(), 'GET');
        $tokens = $this->post($iosFailedCurl,array(), 'GET');
        $Invalidtokens = $this->post($iosInvalidCurl,array(), 'GET');

        $clients = json_decode($clients);
        $tokens = json_decode($tokens);
        $Invalidtokens = json_decode($Invalidtokens);

        $client = array();
        $token = array();
        if($clients)
        {
            foreach($clients as $v)
            {
                $client[] = trim($v[1]);
            }
            !empty($client) && $client = array_values(array_unique($client));
        }
        if($tokens)
        {
            foreach($tokens as $v)
            {
                $token[] = trim($v[1]);
            }
            !empty($token) && $token = array_values(array_unique($token));
        }
        /* 记录日志*/
        $logInfo = '';
        if(!empty($client))
        {
            $logInfo .= '['.date('Y-m-d H:i:s')."]\t安卓推送失败设备:[";
            $logInfo .= implode(',', $client)."]\n";
            foreach ($client as $v) {
                $this->db->query("update r_client set pushFailCount = pushFailCount +1 where client = '{$v}'");
            }
        }
        if(!empty($token))
        {
            $logInfo .= '['.date('Y-m-d H:i:s')."]\tIOS推送失败设备:\t";
            $logInfo .= implode(',', $token)."\n";
            foreach ($token as $v) {
                $this->db->query("update r_client set pushFailCount = pushFailCount +1 where push_token = '{$v}'");
            }
        }
        if(!empty($Invalidtokens))
        {
            $logInfo .= '['.date('Y-m-d H:i:s')."]\tIOS无效token:\t";
            $logInfo .= implode(',', $Invalidtokens)."\n";
            $Invalidtokens = array_unique($Invalidtokens);
            foreach ($Invalidtokens as $v) {
                $this->db->query("update r_client set isPushVaild = 0 where push_token = '{$v}'");
            }
        }
        if($logInfo)
        {
            $this->base->load('log')->writeLog('pushFailLog', $logInfo,'pushFail.txt');
        }

        $this->db->query('update r_client set isPushVaild = 0 where pushFailCount >=10 and isPushVaild = 1');
        return array('client' => count($client), 'token' => count($token), 'Invalidtokens' => count($Invalidtokens));
    }
    /**
     * 创建像这样的查询: "IN('a','b')";
     *
     * @access   public
     * @param    mix      $item_list      列表数组或字符串
     * @param    string   $field_name     字段名称
     *
     * @return   void
     */
    public function db_create_in($item_list, $field_name = '')
    {
        if (empty($item_list))
        {
            return $field_name . " IN ('') ";
        }
        else
        {
            if (!is_array($item_list))
            {
                $item_list = explode(',', $item_list);
            }
            $item_list = array_unique($item_list);
            $item_list_tmp = '';
            foreach ($item_list AS $item)
            {
                if (trim($item) !== '')
                {
                    $item_list_tmp .= $item_list_tmp ? ",'$item'" : "'$item'";
                }
            }
            if (empty($item_list_tmp))
            {
                return $field_name . " IN ('') ";
            }
            else
            {
                return $field_name . ' IN (' . $item_list_tmp . ') ';
            }
        }
    }

    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    const PUSH_ONCE_NUMBER = 2000;//一次推送条数
    
    const DATA_ONCE_NUMBER = 2000;//一次获取Client数量
    
    
    private function getClientDataNumber($type){
    	$count = $this->db->getOne("select count(*) from r_client where client_type = '{$type}'");
    	return ceil($count / self::DATA_ONCE_NUMBER);
    }
    
    private function getClientData($type,$offset,$rows){
    	if($type == 1){
    		$sql = "select client from r_client where client_type = '{$type}' limit $offset, $rows";
    	}else{
    		$sql = "select push_token from r_client where client_type = '{$type}' limit $offset, $rows";
    	}
    	$clientData = $this->db->getCol($sql);
    	return array_chunk($clientData, self::PUSH_ONCE_NUMBER);
    }
    
    
    
    /**
     * 根据uid和data推送通知
     * @param unknown $uid array('uid','uid')
     * @param unknown $data array('title'=>'xxx','body'=>'xxx','url'=>'xxx')
     */
    public function pushNoticeByUid($uid = array(),$data = array()){
    	$result = $this->base->load('client')->getMultiClientId($uid);
    	foreach ($result as $key=>$val){
    		if($val['type'] == '1'){
    			$data = array(
    					"clients"=>$val['token'],
    					"body"=>$data['text'],
    					"title"=>$data['title'],
    					"sound"=>isset($data['sound']) ? $data['sound'] : "0",
    					"url"=>$data['url']
    			);
    		}
    		if($val['type'] == '2'){
    			$data = array(
    					"tokens"=>$val['token'],
    					"body"=>$data['body'],
    					"url"=>$data['url'],
    					"sound"=>isset($data['sound']) ? $data['sound'] : "0",
    			);
    		}
    		$this->pushNotice($val['type'],$data);
    	}
    }
    
    
    /**
     * 获取所有需要推送的数据(状态为推送)
     */
    public function getPushMsg(){
    	return $this->db->getAll('select msg_id,title,android_message,ios_message,url,device_type,is_sound from r_msg_push where status = 0 ');
    }
    
    /**
     * 更新推送通知的状态
     * @param unknown $data
     */
    private function updatePushMsg($id){
    	$this->db->update("update r_msg_push set status = '2' and finish_time = time() where msg_id = '".$id."' ");
    }
    
    /**
     * 记录通知消息发送失败的记录
     */
    private function insertClientPushMsgFailureRecord($type,$data,$result){
    	if($type == 1){
    		$data['client'] = json_encode($result);
    		$data['push_token'] = "";
    	}else {
    		$data['client'] = "";
    		$data['push_token'] = json_encode($result);
    	}
    	
    	$data['push_time'] = time();
    	$data['pust_status'] = '0';
    	
    	$this->db->insertRowTable('r_client_msg_push', $data);
    }
    
    /**
     * 推送批量的通知消息
     * @param unknown $pushMsgData
     */
    public function pushBatchNotice($pushMsgData){
    	
    	foreach ($pushMsgData as $key=>$val){
    		
    		$push_device_type = $val['device_type'];
    		
    		if(in_array($push_device_type,array(0,1))){
    			
    			$number = $this->getClientDataNumber(1);
    			for ($i = 0; $i < $number; $i++){
    				$androidClientData = $this->getClientData(1,($i * self::DATA_ONCE_NUMBER),self::DATA_ONCE_NUMBER);
    				foreach ($androidClientData as $aVal){
    					$data = array(
    							"clients"=>$aVal,
    							"body"=>$val['android_message'],
    							"title"=>$val['title'],
    							"sound"=>$val['is_sound'],
    							"url"=>$val['url']
    					);
    					$this->pushNotice(1,$data);
    				}
     			}
    		}
    		if(in_array($push_device_type,array(0,2))){
    			$number = $this->getClientDataNumber(2);
    			for ($i = 0; $i < $number; $i++){
    				$iosClientData = $this->getClientData(2,($i * self::DATA_ONCE_NUMBER),self::DATA_ONCE_NUMBER);
    				foreach ($iosClientData as $iVal){
    					$data = array(
    							"tokens"=>$iVal,
    							"body"=>$val['ios_message'],
    							"url"=>$val['url'],
    							"sound"=>$val['is_sound']
    					);
    					$this->pushNotice(2,$data);
    				}
    			}
    		}
    		
    		$result = $this->pushFeedback(1);
    		if(json_decode($result)){
    			$this->insertClientPushMsgFailureRecord(1,$val,$result);//插入通知消息记录表
    		}
    		
    		$result = $this->pushFeedback(2);
    		if(json_decode($result)){
    			$this->insertClientPushMsgFailureRecord(2,$val,$result);//插入通知消息记录表
    		}
    		
    		$this->updatePushMsg($val['msg_id']);//修改当前通知消息的状态(表示通知已经发送,至于有没有收到或发送是否送达后面处理)
    	}
    }
    
    
	/**
	 * 通知推送
	 * @param number $deviceType	设备类型 (1:android;2:ios)
	 * @param array $data
	 * @return boolean
	 */
	public function pushNotice($deviceType = 1, $data){
		
		if(!in_array($deviceType,array(1,2))){
			return false;
		}
		switch ($deviceType){
			case 1:
				return $this->postNotice($this->getAndroidNoticeUrl(),$this->getAndroidNoticeData($data));
				break;
			case 2:
				return $this->postNotice($this->getIosNoticeUrl(),$this->getIosNoticeData($data));
				break;
		}
	}
	
	/**
	 * 通知推送反馈
	 * @param number $deviceType
	 * @return boolean|unknown
	 */
	public function pushFeedback($deviceType = 1){
		if(!in_array($deviceType,array(1,2))){
			return false;
		}
		
		switch ($deviceType){
			case 1:
				return $this->postFeedback($this->getAndroidNoticFeedbackUrl());
				break;
			case 2:
				$feedback = $this->postFeedback($this->getIosNoticeFeedbackUrl());
				$invtoken = $this->postFeedback($this->getIosNoticeInvtokenUrl());
				return empty($feedback) ? $invtoken  : $feedback;
				break;
		}
	}
	
	/**
	 * 获取android通知推送数据
	 * @param unknown $data
	 * @return array
	 */
	private function getAndroidNoticeData($data){
		return array(
				'clients' => $data['clients'],
				'expiry' => time() + 3600,
				'payload' => array(
						'aps' => array(
								'alert' => array(
										'body' => $data['body'],
										'title' => $data['title'],
										'action-loc-key' => '',
										'loc-key' => '',
										'loc-args' => '',
										'launch-image' => '',
								),
								'sound' => $data['sound'],
						),
						'url' => $data['url']
				),
		);
	}
	
	/**
	 * 获取android通知url
	 * @return string
	 */
	private function getAndroidNoticeUrl(){
		return "http://". $this->apnsArr['host'] . ":" . $this->apnsArr['port'] . "/droid/notific/" . $this->apnsArr['appIdentifier'];
	}
	
	/**
	 * 获取ios通知推送数据
	 * @param array $data
	 * @return array
	 */
	private function getIosNoticeData($data){
		return array(
				'tokens' => $data['tokens'],
				'expiry' => time() + 1800,
				'payload' => array(
						'aps' => array(
								'alert' => array(
										'body' => $data['body'],
										'action-loc-key' => '',
										'loc-key' => '',
										'loc-args' => '',
										'launch-image' => 'LaunchImage',
								),
								'sound' => $data['sound'],
						),
						'url' => $data['url'],
				)
		);
	}
	
	/**
	 * 获取ios通知url
	 * @return string
	 */
	private function getIosNoticeUrl(){
		return "http://". $this->apnsArr['host'] . ":" . $this->apnsArr['port'] . "/ios/notific/" . $this->apnsArr['appIdentifier'];
	}
	
	/**
	 * 具体推送通知
	 * @param unknown $post_curl
	 * @param unknown $data
	 * @return number
	 */
	private function postNotice($post_curl, $data){
		return $this->post($post_curl, json_encode($data)) == '"+OK"' ? 1 : 0;
	}
	
	/**
	 * 具体推送通知反馈
	 * @param unknown $post_curl
	 */
	private function postFeedback($post_curl){
		return $this->post($post_curl, array(), 'GET');
	}
	
	/**
	 * 获取android通知反馈url(未送达)
	 * @return string
	 */
	private function getAndroidNoticFeedbackUrl(){
		return "http://" . $this->apnsArr['host'] . ":" . $this->apnsArr['port'] . '/droid/feedback/' . $this->apnsArr['appIdentifier'];
	}
	
	/**
	 * 获取ios通知token反馈url(未送达)
	 */
	public function getIosNoticeFeedbackUrl(){
		return "http://". $this->apnsArr['host'] . ":" . $this->apnsArr['port'] . "/ios/feedback/" . $this->apnsArr['appIdentifier'];
	}
	
	/**
	 * 获取ios通知token反馈url(无效)
	 */
	private function getIosNoticeInvtokenUrl(){
		return "http://". $this->apnsArr['host'] . ":" . $this->apnsArr['port'] . "/ios/invtoken/" . $this->apnsArr['appIdentifier'];
	}
}
